<?php

namespace Icsoc\InstallBundle\Composer;

use Sensio\Bundle\DistributionBundle\Composer\ScriptHandler as SensioScriptHandler;

use Composer\Script\CommandEvent;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

class ScriptHandler extends SensioScriptHandler
{
    /**
     * Create empty database for cache:clear
     *
     * @param CommandEvent $event
     */
    public static function createEmptyDatabase(CommandEvent $event)
    {
        $options = self::getOptions($event);
        $parameters = Yaml::parse(file_get_contents(__DIR__.'/../../../../'.$options['incenteev-parameters']['file']));
        $host = $parameters['parameters']['database_host'];
        $user = $parameters['parameters']['database_user'];
        $password = $parameters['parameters']['database_password'];
        $port = $parameters['parameters']['database_port'];
        $database = $parameters['parameters']['database_name'];

        $commandLine = sprintf('mysqladmin -h%s -u%s -p%s -P%s create %s', $host, $user, $password, $port, $database);
        $process = new Process(null);
        $process->setCommandLine($commandLine);
        $process->setTimeout(null);
        $process->run();
        if (!$process->isSuccessful()) {
            $errorOutPut = $process->getErrorOutput();
            //如果是数据库已存在，则不处理
            if (strstr($errorOutPut, 'database exists')) {
                $event->getIO()->write(sprintf('The database <info>%s</info> aleady exists.', $database));
            } else {
                throw new ProcessFailedException($process);
            }
        }
    }

    /**
     * 创建日志目录
     *
     * @param CommandEvent $event
     */
    public static function createLogDir(CommandEvent $event)
    {
        $fs = new Filesystem();

        if (!is_dir('/var/log/manage')) {
            try {
                $fs->mkdir('/var/log/manage/', 0777);
                $fs->chmod('/var/log/manage/', 0777);
            } catch (IOExceptionInterface $e) {
                $event->getIO()->write(sprintf('创建目录 <strong>%s</strong> 失败', $e->getPath()));
            }
        }
    }

    /**
     * Set permissions for directories
     *
     * @param CommandEvent $event
     */
    public static function setPermissions(CommandEvent $event)
    {
        $options = self::getOptions($event);

        $webDir = isset($options['symfony-web-dir']) ?
            $options['symfony-web-dir'] : 'web';

        $parametersFile = isset($options['incenteev-parameters']['file']) ?
            $options['incenteev-parameters']['file'] : 'app/config/parameters.yml';

        $directories = array(
            'app/cache',
            'app/logs',
            'app/data',
            'app/data/locale.db',
            '/var/log/manage/dev.log',
            $webDir,
            $parametersFile
        );

        $permissionHandler = new PermissionsHandler();
        foreach ($directories as $directory) {
            $event->getIO()->write(sprintf('Chmod directory <info> %s </info>.', $directory));
            $permissionHandler->setPermissions($directory);
        }

        $event->getIO()->write(sprintf('<info>修改目录权限成功</info>'));
    }

    /**
     * Dump assetic files
     *
     * @param CommandEvent $event
     */
    public static function assticDump(CommandEvent $event)
    {
        $consoleDir = self::getConsoleDir($event, 'assetic dump');

        if (null === $consoleDir) {
            return;
        }

        $env = 'prod';
        $event->getIO()->write(sprintf('Dump assetic for the <info> %s </info> mode.', $env));
        static::executeCommand($event, $consoleDir, 'assetic:dump --env='.$env);
    }
}
